#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# gui runtime
############################################################################
#    Copyright (C) 2007 by Håvard Gulldahl                                 #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import sys, types, logging, os, datetime

import storm.locals as storm

from PyQt4 import QtGui, QtCore
from gui_ui import Ui_MainWindow

sys.path.append(os.path.abspath('..'))

import jeje


class ejejeGui(QtGui.QMainWindow):

    startuppath = ''
    pathlist = []

    def __init__(self, mainApp):
        QtGui.QDialog.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.model.setHeaderLabels( ['Object',] )

        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.update)
        QtCore.QObject.connect(self.ui.model, QtCore.SIGNAL('itemSelectionChanged()'), self.edit)

    def loadIntoModel(self, database):
        self.database = database
        for t in ( jeje.ejeje_saksbehandler, jeje.ejeje_postjournal,
                   jeje.ejeje_adressat, jeje.ejeje_feil, jeje.ejeje_postjournal_logg,
                   jeje.ejeje_journalpost, jeje.ejeje_organisasjon, jeje.ejeje_enkeltjournal ):
            n = t.__storm_table__
            self.addBranch(n, database.find(t))



    def addBranch(self, name, items):
        top = QtGui.QTreeWidgetItem(self.ui.model, [name,])
        c = []
        for i in items:
            q = QtGui.QTreeWidgetItem(top, ['ID #%i' % i.id, ])
            q.obj = i
            c.append(q)
        top.addChildren(c)

        self.ui.model.addTopLevelItem(top)

    def edit(self):
        item = self.ui.model.selectedItems()[0]
        if item.childCount() > 0: return # top level
        self.populateEditor(item.obj)
        #print self.ui.viewer.layout()

    def populateEditor(self, obj):
        self.ui.viewer.setTitle(obj.__storm_table__) # set title
        layout = self.ui.viewer.layout()
        if layout is None:
            layout = QtGui.QVBoxLayout(self.ui.viewer)
            layout.addStretch(1)
        else:
            for row in layout.children(): 
                for i in range(row.count()):
                    w = row.itemAt(i).widget()
                    layout.removeWidget(w)
                layout.removeItem(row)
                row.deleteLater() # empty container
            
        for f in dir(obj):
            if f.startswith('_') or f.startswith('sett_') or f == 'id':
                continue
            w = self.createInputWidget(getattr(obj, f))
            if w is None:
                continue
            w.object = (obj, f)
            row = QtGui.QHBoxLayout()
            #print f
            l = QtGui.QLabel('%s:' % f, self.ui.viewer)
            row.addWidget(l)
            row.addWidget(w)
            layout.addLayout(row)

    def createInputWidget(self, obj):
        #print type(obj)
        if isinstance(obj, ( types.MethodType, types.ClassType,
                             jeje.ejeje_organisasjon, jeje.ejeje_postjournal,
                             jeje.ejeje_adressat, jeje.ejeje_saksbehandler,
                             jeje.ejeje_enkeltjournal, jeje.ejeje_feil) ):
            return None
        elif isinstance(obj, types.BooleanType):
            w = QtGui.QComboBox(self.ui.viewer)
            choices = [ 'True', 'False' ]
            w.addItems( choices )
            w.setCurrentIndex( choices.index(str(obj)) )
        elif isinstance(obj, ( types.IntType, types.LongType )):
            w = QtGui.QSpinBox(self.ui.viewer)
            w.setRange(-50000,50000)
            w.setValue(obj)
        elif isinstance(obj, datetime.datetime):
            w = QtGui.QDateTimeEdit(self.ui.viewer)
            date = QtCore.QDate(obj.year, obj.month, obj.day)
            time = QtCore.QTime(obj.hour, obj.minute, obj.second)
            w.setDateTime(QtCore.QDateTime(date, time))
        elif isinstance(obj, datetime.date):
            w = QtGui.QDateEdit(self.ui.viewer)
            w.setDate(QtCore.QDate(obj.year, obj.month, obj.day))
        elif isinstance(obj, jeje.ejeje_uri):
            w = QtGui.QLineEdit(self.ui.viewer)
            w.klass = jeje.ejeje_uri
            w.setText(obj.uri)
        else:
            s = unicode(obj)
            if len(s) > 80:
                w = QtGui.QTextEdit(self.ui.viewer)
                w.setAcceptRichText(False)
                w.setMaximumHeight(90)
                w.setPlainText(s)
            else:
                w = QtGui.QLineEdit(self.ui.viewer)
                w.setText(s)
        return w

    def readInputWidget(self, widget):
        if hasattr(widget, 'dateTime'):
            d = widget.dateTime()
            return d.toPyDateTime()
        elif hasattr(widget, 'text'):
            r = unicode(widget.text())
            if r.isnumeric(): return int(r)
            else: return r
        elif hasattr(widget, 'value'):
            return float(widget.value())
        elif hasattr(widget, 'currentText'):
            t = unicode(widget.currentText())
            if t in ( 'True', 'False' ): return eval(t)
            return t
        elif hasattr(widget, 'toPlainText'):
            return unicode(widget.toPlainText())
        print "ukjent w:",widget
        return None

    def update(self):
        print "update"
        dirty = False
        for w in self.ui.viewer.children():
            if hasattr(w, 'object'):
                value = self.readInputWidget(w)
                if value is None or value == 'None': continue
                if hasattr(w, 'klass'):
                    value = w.klass(value)
                _type = type(getattr(w.object[0], w.object[1]))
                print 'setter %s (%s): %s' % (w.object[1], _type, value)
                setattr(w.object[0], w.object[1], value)
                dirty = True
        if dirty:
            self.database.commit()

if __name__ == "__main__":
    db_filename = os.path.abspath('../ejeje.db')
    if False:
        db_filename = '' # in memory
    first_run = not os.path.exists(db_filename)
    connection_string = 'sqlite:' + db_filename #+ '?debug=true'
    logging.debug('Kobler til storm: %s', db_filename)
    database = storm.create_database(connection_string)
    store = storm.Store(database)

    app = QtGui.QApplication(sys.argv)
    ejeje = QtGui.QMainWindow()
    ui = ejejeGui(ejeje)
    ui.show()
    ui.loadIntoModel(store)
    sys.exit(app.exec_())
